package com.taotao.manager.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.taotao.common.pojo.EasyUiDataGridResult;
import com.taotao.common.pojo.TaotaoResult;
import com.taotao.common.util.CommonUtil;
import com.taotao.common.util.IDUtils;
import com.taotao.common.util.JsonUtils;
import com.taotao.manager.jedis.JedisClient;
import com.taotao.manager.mapper.TbItemDescMapper;
import com.taotao.manager.mapper.TbItemMapper;
import com.taotao.manager.pojo.TbItem;
import com.taotao.manager.pojo.TbItemDesc;
import com.taotao.manager.pojo.TbItemExample;
import com.taotao.manager.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.jms.*;
import java.util.Date;
import java.util.List;

@Service
public class ItemServiceImpl implements ItemService {
    @Autowired
    private TbItemMapper itemMapper;
    @Autowired
    private TbItemDescMapper itemDescMapper;
    @Autowired
    private JmsTemplate jmsTemplate;
    //使用@resource注解，并且指定name   在spring容器中包含多个该类型的对象
    @Resource(name = "topicDestination")
    private Destination topicDestination;
    @Autowired
    private JedisClient jedis;
    @Value("${ITEM_INFO_KEY}")
    private String ITEM_INFO_KEY;
    @Value("${ITEM_INFO_KEY_EXPIRE}")
    private Integer ITEM_INFO_KEY_EXPIRE;

    @Override
    public EasyUiDataGridResult getItemList(Integer page, Integer rows) {
        //设置分页信息
        //创建查询条件的example  --不需要查询条件
        //使用注入的mapper查询数据
        //获取分页的信息
        //封装到EasyUiDataGridResult对象中，并返回
        PageHelper.startPage(page, rows);
        TbItemExample example=new TbItemExample();
        List<TbItem> itemList = itemMapper.selectByExample(example);
        PageInfo<TbItem> pageInfo=new PageInfo<>(itemList);
        EasyUiDataGridResult result = new EasyUiDataGridResult();
        result.setTotal(pageInfo.getTotal());
        result.setRows(pageInfo.getList());

        return result;
    }

    @Override
    public TaotaoResult saveItem(TbItem item, String desc) {
        final long itemId = IDUtils.genItemId();
        item.setId(itemId);
        //商品状态，1-正常，2-下架，3-删除
        item.setStatus((byte)1);
        Date date = new Date();
        item.setCreated(date);
        item.setUpdated(date);
        itemMapper.insert(item);

        TbItemDesc itemDesc = new TbItemDesc();
        itemDesc.setItemId(itemId);
        itemDesc.setItemDesc(desc);
        itemDesc.setCreated(date);
        itemDesc.setUpdated(date);

        itemDescMapper.insert(itemDesc);
        //添加发送mq消息的业务逻辑，而且必须是commit成功之后再发送
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {
                sendMQ(itemId+"");
            }
        });

        return TaotaoResult.ok();
    }

    @Override
    public TaotaoResult updateItem(TbItem item, String desc) {
        Date date = new Date();
        item.setUpdated(date);
        TbItem tbItem = itemMapper.selectByPrimaryKey(item.getId());
        CommonUtil.copyPropertiesIgnoreNull(item,tbItem);
        itemMapper.updateByPrimaryKey(tbItem);
        if(!StringUtils.isEmpty(desc)){
            TbItemDesc itemDesc = itemDescMapper.selectByPrimaryKey(item.getId());
            itemDesc.setUpdated(date);
            itemDesc.setItemDesc(desc);
            itemDescMapper.updateByPrimaryKey(itemDesc);
        }
        return TaotaoResult.ok();
    }

    @Override
    public TaotaoResult deleteItem(Long id) {
        itemMapper.deleteByPrimaryKey(id);
        return TaotaoResult.ok();
    }

    @Override
    public TaotaoResult deleteBatchItem(String ids) {
        if(!StringUtils.isEmpty(ids)){
            String[] idss = ids.split(",");
            for(String idStr:idss){
                Long id = Long.parseLong(idStr);
                itemMapper.deleteByPrimaryKey(id);
                itemDescMapper.deleteByPrimaryKey(id);
            }
        }
        return TaotaoResult.ok();
    }

    @Override
    public TbItem getItemById(Long itemId) {
        String key = ITEM_INFO_KEY + ":" + itemId + ":BASE";
        try {
            String jsonStr = jedis.get(key);
            if (!StringUtils.isEmpty(jsonStr)) {
                System.out.println("有缓存");
                jedis.expire( key, ITEM_INFO_KEY_EXPIRE);
                return JsonUtils.jsonToPojo(jsonStr, TbItem.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        TbItem tbItem = itemMapper.selectByPrimaryKey(itemId);
        try {
            jedis.set(key, JsonUtils.objectToJson(tbItem));
            jedis.expire( key, ITEM_INFO_KEY_EXPIRE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tbItem;
    }

    //发送MQ消息
    private void sendMQ(final String message){
        jmsTemplate.send(topicDestination , new MessageCreator() {
            @Override
            public Message createMessage(Session session) throws JMSException {
                //发送的消息
                TextMessage textMessage = session.createTextMessage( message);
                return textMessage;
            }
        });
    }

}
